package com.media.aop;

import com.base.model.ExceptionLog;
import com.base.model.RequestLog;
import com.base.model.ResponseLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

/**
 * @Author: 小何
 * @Description: TODO
 * @DateTime: 2023/11/6 10:48
 **/
@Aspect
@Component
public class LogAop {

    Logger logger = LoggerFactory.getLogger(LogAop.class);

    @Pointcut("execution(* com.media.api.*.*(..))")
    public void pointCut() {

    }

    @Around(value = "pointCut()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
        String logId = UUID.randomUUID().toString().replaceAll("-", "");
        RequestLog requestLog = new RequestLog();
        requestLog.setLogId(logId);
        requestLog.setRequestMethod(proceedingJoinPoint.getSignature().getName());
        Object[] args = proceedingJoinPoint.getArgs();
        requestLog.setRequestData(Arrays.toString(args));
        logger.error(requestLog.toString());
        try {
            Object obj = proceedingJoinPoint.proceed();
            ResponseLog responseLog = new ResponseLog();
            responseLog.setLogId(logId);
            responseLog.setResponseData(obj.toString());
            logger.error(responseLog.toString());
            return obj;
        } catch (Throwable throwable) {
            ExceptionLog exceptionLog = new ExceptionLog();
            exceptionLog.setMessage(throwable.getMessage());
            exceptionLog.setLogId(logId);
            logger.error(exceptionLog.toString());
            throwable.printStackTrace();
        }
        return null;
    }

}
